package org.aurora.remote.netty;

import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;
import org.aurora.common.util.NetworkUtil;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class NettyConnectManager implements NettyEventSubscriber {

    private final Map<String/*ip+:+port*/, Channel> CHANNEL_MAP = new ConcurrentHashMap<>();

    @Override
    public String getSubscriberName() {
        return "nettyConnectManager";
    }

    @Override
    public void connect(NettyEvent event) {
        Channel channel = event.getChannel();
        String ip = event.getIp();
        int port = event.getPort();
        String addr = NetworkUtil.splicingAddr(ip, port);

        this.CHANNEL_MAP.put(addr, channel);
    }

    @Override
    public void disconnect(NettyEvent event) {
        String addr = NetworkUtil.splicingAddr(event.getIp(), event.getPort());
        this.closeChannel(addr);
    }

    @Override
    public void exception(NettyEvent event) {
        String addr = NetworkUtil.splicingAddr(event.getIp(), event.getPort());
        this.closeChannel(addr);
    }

    public Channel getChannel(String addr) {
        return this.CHANNEL_MAP.get(addr);
    }

    public void closeChannel(String addr) {
        if (StringUtils.isBlank(addr)) {
            return;
        }

        try {
            Channel channel = this.CHANNEL_MAP.remove(addr);
            if (channel != null) {
                channel.close();

                log.info("close connect success, addr = {}", addr);
            } else {
                log.info("close connect channel is null, addr = {}", addr);
            }
        } catch (Exception e) {
            log.error("close connect error, addr = {}", addr);
        }
    }
}
